package com.wfs;
import java.io.IOException;
import javax.servlet.http.*;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.wfs.datastore.PairSessionDatastore;
import com.wfs.util.GCMServiceUtil;



public class PairDevicesController extends HttpServlet {
	

	public static final String PARAMETER_TOKEN = "token";
	public static final String PARAMETER_ACTION = "action";
	public static final String PARAMETER_DEVICE_RID = "device_rid";
	
	public static final int ACTION_ACK = 1;
	public static final int ACTION_CONNECT = 2;
	public static final int ACTION_TERMINATE = 3;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		new PairSessionDatastore();
		String action = req.getParameter(PARAMETER_ACTION);
		String token = req.getParameter(PARAMETER_TOKEN);
		String device_rid = req.getParameter(PARAMETER_DEVICE_RID);
		if(action != null){
			switch(Integer.parseInt(action)){
			case ACTION_ACK:
				if(token != null){
					PairSessionDatastore.putSession(token,PairSessionDatastore.ACKNOWLEDGED_STATE,device_rid);
					//Acknowledge device
					GCMServiceUtil.sendMessage(device_rid, "ACKNOWLEDGED");
				}
				break;
			case ACTION_CONNECT:
				//Connection established when device acknowledges response from server
				if(token != null){
					PairSessionDatastore.putSession(token,PairSessionDatastore.CONNECTED_STATE,device_rid);
					GCMServiceUtil.sendMessage(device_rid, "CONNECTED");
				}
				break;
			case ACTION_TERMINATE:
				//Connection terminated when device initiates termination
				if(token != null){
					PairSessionDatastore.putSession(token,PairSessionDatastore.TERMINATED_STATE,device_rid);
					GCMServiceUtil.sendMessage(device_rid, "TERMINATED");
				}
				break;
			}
		}
	}
	
}
